package com.cf.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;

/**
 * MyBatis基础配置
 *
 */

@Configuration
public class MyBatisConfig {
	@Autowired
	private DataSource dataSource;

	@Bean(name = "sqlSessionFactory")
	@Primary
	public SqlSessionFactory sqlSessionFactoryBean() {
		MybatisSqlSessionFactoryBean sqlsession = new MybatisSqlSessionFactoryBean();
		sqlsession.setDataSource(dataSource);

		// 扫描entity包 使用别名
		sqlsession.setTypeAliasesPackage("com.cf.entity");
		MybatisConfiguration configuration = new MybatisConfiguration();
		// 使用jdbc的getGeneratedKeys获取数据库自增主键值
		configuration.setUseGeneratedKeys(true);
		// 使用列别名替换列名 select user as User
		configuration.setUseColumnLabel(true);
		// -自动使用驼峰命名属性映射字段 userId user_id
		configuration.setMapUnderscoreToCamelCase(false);
		configuration.setJdbcTypeForNull(JdbcType.NULL);
		configuration.setCallSettersOnNulls(true);
		// configuration.addInterceptor(new MybatisInterceptor());
		// configuration.addInterceptor(new InterceptorForQry());
		// configuration.setLogImpl((Class<? extends Log>) Log4j.class);
		sqlsession.setConfiguration(configuration);
		sqlsession.setFailFast(true);

		// 添加XML目录
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		try {
			sqlsession.setMapperLocations(
					resolver.getResources("classpath:mapper/*.xml"));
			return sqlsession.getObject();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	@Bean()
	@Primary
	public SqlSessionTemplate sqlSessionTemplate(
			SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

	@Bean()
	@Primary
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		return new DataSourceTransactionManager(dataSource);
	}
}